package com.joint.web.action.mp;

import com.fz.us.base.util.LogUtil;
import com.joint.base.mp.WxEchoMpMessageRouter;
import com.joint.base.mp.WxMpInCacheConfigStorage;
import com.joint.web.action.BaseAdminAction;
import fz.me.chanjar.weixin.mp.api.WxMpService;
import fz.me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import fz.me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 后台Action类 - 导航
 * ============================================================================
 * 版权所有 2014 。
 * 
 * @author min_xu
 * 
 * @version 0.1 2014-01-20
 * @version 0.2 2014-07-30 update by fallenpanda
 * ============================================================================
 */

@ParentPackage("mp")
public class WechatAction extends BaseAdminAction {
	private static final long serialVersionUID = -1813109372714169049L;

    private String nonce;
    private String signature;

    public String getEchostr() {
        return echostr;
    }

    public void setEchostr(String echostr) {
        this.echostr = echostr;
    }
    private String echostr;

    @Resource
    private WxMpService wxMpService;
    @Resource
    private WxMpInCacheConfigStorage wxMpConfigStorage;
    @Resource
    private WxEchoMpMessageRouter wxMpMessageRouter;

    public String execute() throws IOException {
        LogUtil.info("{wechart start}");
        String method = getRequest().getMethod();
        boolean isPostMethod = "POST".equalsIgnoreCase(method);
        String signature = getRequest().getParameter("signature");
        String nonce = getRequest().getParameter("nonce");
        String timestamp = getRequest().getParameter("timestamp");
        //LogUtil.info(signature + " " + nonce + " " + timestamp + " getToken:" + wxMpConfigStorage.getToken());
        getResponse().setContentType("text/html;charset=utf-8");
        getResponse().setStatus(HttpServletResponse.SC_OK);
/*        try {
            LogUtil.info(SHA1.gen(wxMpConfigStorage.getToken(), timestamp, nonce));
        } catch (NoSuchAlgorithmException e) {

        }*/
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            return ajaxText("非法请求");
        }
        if (!isPostMethod) {
            //Get
            String echostr = getRequest().getParameter("echostr");
            //LogUtil.info("echostr"+echostr);
            if (StringUtils.isNotBlank(echostr)) {
                // 说明是一个仅仅用来验证的请求，回显echostr
                return ajaxText(echostr);
            }
        } else {
            //POST
            String encryptType = StringUtils.isBlank(getRequest().getParameter("encrypt_type")) ?
                    "raw" :
                    getRequest().getParameter("encrypt_type");
            //System.out.println("encryptType:"+encryptType);
            WxMpXmlMessage inMessage = null;
            if ("raw".equals(encryptType)) {
                // 明文传输的消息
                try {
                    inMessage = WxMpXmlMessage.fromXml(getRequest().getInputStream());
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            } else if ("aes".equals(encryptType)) {
                // 是aes加密的消息
                String msgSignature = getRequest().getParameter("msg_signature");
                inMessage = WxMpXmlMessage.fromEncryptedXml(getRequest().getInputStream(), wxMpConfigStorage, timestamp, nonce, msgSignature);
            } else {
                return ajaxText("不可识别的加密类型");
            }
            //LogUtil.info("{inMessage.getFromUserName()}"+inMessage.getFromUserName()  + " {inMessage.getToUserName()}" + inMessage.getToUserName());
            LogUtil.info("{inMessage.getEvent()}" + inMessage.getEvent());
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            LogUtil.info("{encryptType}" + encryptType + "{outMessage}" + outMessage.toXml());
            if (outMessage != null) {
                if ("raw".equals(encryptType)) {
                    getResponse().getWriter().write(outMessage.toXml());
                } else if ("aes".equals(encryptType)) {
                    getResponse().getWriter().write(outMessage.toEncryptedXml(wxMpConfigStorage));
                }
                return null;
            }
            return null;
        }
        return null;
    }

    public String getNonce() {
        return nonce;
    }

    public void setNonce(String nonce) {
        this.nonce = nonce;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }
}
